package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.ORDER_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.ORDER_PAY_KEY;
import static com.tianji.common.constants.MqConstants.Key.ORDER_REFUND_KEY;
import static com.tianji.common.constants.MqConstants.Queue.LEARNING_LESSON_PAY_QUEUE;

/**
 * @author Administrator
 * @version 1.0
 * @description: 课程变动监听器
 * @date 2024/11/6 15:01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {
    private final ILearningLessonService lessonService;

    /**
     * 1、监听订单支付消息 -> 新增课程到用户的课表（Day2 - 课堂）
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = LEARNING_LESSON_PAY_QUEUE, durable = "true"),
            exchange = @Exchange(name = ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = ORDER_PAY_KEY
    ))
    public void listenOrderPayMsg(OrderBasicDTO orderMsg){
        // 1、消息健壮性判断
        if(ObjectUtil.isEmpty(orderMsg) || ObjectUtil.isEmpty(orderMsg.getUserId()) || ObjectUtil.isEmpty(orderMsg.getCourseIds())){
            log.error("订单支付消息格式异常，消息：{}", orderMsg);
            return;
        }

        // 2、添加课程至课表
        log.info("监听到用户：{}的订单{}的支付消息，需要添加课程：{}至用户的课表", orderMsg.getUserId(),orderMsg.getOrderId(), orderMsg.getCourseIds());
        lessonService.addLessons(orderMsg.getUserId(),orderMsg.getCourseIds());
    }

    /**
     * 2、监听取消订单消息 -> 删除课程（Day2 - 作业6）
     * @param order
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.refund.queue", durable = "true"),
            exchange = @Exchange(name = ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = ORDER_REFUND_KEY
    ))
    public void listenLessonRefund(OrderBasicDTO order){
        // 1.健壮性处理
        if(order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())){
            // 数据有误，无需处理
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        // 2.添加课程
        log.debug("监听到用户{}的订单{}要退款，需要删除课程{}", order.getUserId(), order.getOrderId(), order.getCourseIds());
        lessonService.deleteCourseFromLesson(order.getUserId(), order.getCourseIds().get(0));
    }
}
